﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using System.Xml.Linq;
using System.IO;
using Microsoft.Win32;

namespace FontParser
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public List<FontData> fonts = new List<FontData>();
        public Dictionary<string, string> fontUris = new Dictionary<string, string>();
        public Window1()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Window1_Loaded);
        }

        void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            ICollection<FontFamily> fontFamilies = Fonts.SystemFontFamilies;
            string system = System.Environment.SystemDirectory;
            int idx = system.LastIndexOf('\\');
            system = system.Substring(0, idx);
            string[] files = Directory.GetFiles(system + "\\fonts", "*.ttf");
            foreach (string file in files)
            {
                GlyphTypeface t = new GlyphTypeface(new Uri(file));
                foreach (string familyName in t.FamilyNames.Values)
                {
                    if (fontUris.ContainsKey(familyName) == false)
                    {
                        fontUris.Add(familyName, file);
                    }
                }
            }

            foreach (FontFamily f in fontFamilies)
            {
                foreach (string font in f.FamilyNames.Values)
                {
                    FontData fd = new FontData();
                    fd.FontName = font;
                    fd.FontFamily = f;
                    fonts.Add(fd);
                }
            }
            comboBox1.ItemsSource = fonts;
        }

        private void SaveFont()
        {
            FontData fd = comboBox1.SelectedItem as FontData;
            string fontPath = fontUris[fd.FontName];
            int size = 12;
            int.TryParse(fontSize.Text, out size);
            GlyphTypeface gt = new GlyphTypeface(new Uri(fontPath, UriKind.Absolute));
            IDictionary<ushort, double> widths = gt.AdvanceWidths;
            IDictionary<ushort, double> heights = gt.AdvanceHeights;
            IDictionary<ushort, double> leftSide = gt.LeftSideBearings;
            IDictionary<ushort, double> rightSide = gt.RightSideBearings;
            IDictionary<ushort, double> bottomSide = gt.BottomSideBearings;
            IDictionary<ushort, double> topSide = gt.TopSideBearings;
            IDictionary<int, ushort> glyphMap = gt.CharacterToGlyphMap;

            double baseline = gt.Baseline;
            XDocument doc = new XDocument(new XElement("font", 
                new XAttribute("baseline", baseline),
                new XAttribute("height", gt.Height),
                new XAttribute("pointSize", size)
                ));
            XElement root = doc.Root;



            foreach (ushort glyph in glyphMap.Keys)
            {
                ushort key = glyphMap[glyph];
                Geometry g = gt.GetGlyphOutline(key, size, size);
                XElement ele = new XElement("glyph",
                    new XAttribute("key", glyph),
                    new XAttribute("advance", string.Format("{0},{1}", widths[key], heights[key])),
                    new XAttribute("bearings", string.Format("{0},{1},{2},{3}", leftSide[key], topSide[key], rightSide[key], bottomSide[key])),
                    new XAttribute("path", g.ToString()));
                root.Add(ele);
            }
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = fd.FontName + size.ToString() + ".xfn";
            dlg.AddExtension = true;
            dlg.DefaultExt = ".xfn";
            bool? ret = dlg.ShowDialog();
            if (ret != null && ret.Value == true)
            {
                doc.Save(dlg.FileName);
                MessageBox.Show("Save Complete");
            }
        }

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                FontData fd = e.AddedItems[0] as FontData; 
                sampleTextBlock.FontFamily = new FontFamily(fd.FontName);
            }
        }

        private void UpdateFontSize()
        {
            if (sampleTextBlock == null) return;
            int size = -1;
            int.TryParse(fontSize.Text, out size);
            if (size > 0)
            {
                sampleTextBlock.FontSize = size;
            }
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (sampleTextBlock != null)
            {
                sampleTextBlock.Text = sampleTextBox.Text;
            }
        }



        private void fontSize_TextChanged(object sender, TextChangedEventArgs e)
        {
            UpdateFontSize();
        }

        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            SaveFont();
        }
    }
}
